import { registerMicroApps, start, initGlobalState } from 'qiankun'
import router from '@/router'
import { setGlobalActions, setMainAppData } from './qiankun'

// 初始化全局状态
// 注意：qiankun 3.0 将移除 globalState，但目前仍需使用
// 未来可考虑使用 EventBus 或其他状态管理方案替代
const initialState = {
    user: { id: null, name: '', token: '', permissions: [] },
    theme: 'light',
    language: 'zh-CN',
    subAppRoute: '',
    sharedData: {
        currentProject: null,
        notifications: [],
        settings: {}
    }
}

const actions = initGlobalState(initialState)

// 本地状态管理 - 解决 qiankun actions 没有 getGlobalState 方法的问题
let currentGlobalState = { ...initialState }

// 监听状态变化，更新本地状态
actions.onGlobalStateChange((state, prev) => {
    console.log('[主应用] 全局状态变化:', { state, prev })
    currentGlobalState = { ...state }
})

// 包装 setGlobalState 方法，同时更新本地状态
const originalSetGlobalState = actions.setGlobalState
actions.setGlobalState = (state) => {
    currentGlobalState = { ...currentGlobalState, ...state }
    return originalSetGlobalState.call(actions, state)
}

// 添加 getGlobalState 方法
actions.getGlobalState = () => {
    return { ...currentGlobalState }
}

// 主应用数据管理器
export const mainAppData = {
    setUser(userInfo) {
        actions.setGlobalState({ user: { ...userInfo } })
        console.log('[主应用] 用户信息已更新:', userInfo)
    },

    setTheme(theme) {
        actions.setGlobalState({ theme })
        console.log('[主应用] 主题已切换:', theme)
    },

    setLanguage(language) {
        actions.setGlobalState({ language })
        console.log('[主应用] 语言已切换:', language)
    },

    sendNotification(notification) {
        const currentState = actions.getGlobalState()
        const notifications = [...(currentState.sharedData?.notifications || []), {
            id: Date.now(),
            timestamp: new Date().toISOString(),
            ...notification
        }]

        actions.setGlobalState({
            sharedData: { ...currentState.sharedData, notifications }
        })
        console.log('[主应用] 发送通知:', notification)
    },

    updateSharedData(data) {
        const currentState = actions.getGlobalState()
        actions.setGlobalState({
            sharedData: { ...currentState.sharedData, ...data }
        })
        console.log('[主应用] 共享数据已更新:', data)
    },

    getState() {
        return actions.getGlobalState()
    },

    // 导航到子应用
    navigateToSubApp(appName, path = '') {
        const fullPath = `/${appName}${path}`
        if (router.currentRoute.value.path !== fullPath) {
            router.push(fullPath)
        }
        console.log('[主应用] 导航到子应用:', fullPath)
    }
}

// 设置到 qiankun 工具类中
setGlobalActions(actions)
setMainAppData(mainAppData)

// 通用的子应用配置
const createSubAppConfig = (name, port) => ({
    name,
    entry: getSubAppEntry(name, port),
    container: '#subapp-viewport',
    activeRule: `/${name}`,
    props: {
        routerBase: `/${name}`,
        actions,
        mainAppData,
        setMainAppRoute: (path) => {
            const fullPath = `/${name}${path}`
            if (router.currentRoute.value.path !== fullPath) {
                router.push(fullPath)
            }
        },
        mainAppInfo: { name: 'qiankun-main', version: '1.0.0' },
        utils: {
            showMessage: (message, type = 'info') => {
                console.log(`[主应用消息-${type}]:`, message)
            },
            showConfirm: (message) => Promise.resolve(confirm(message))
        }
    }
})

// 获取子应用的入口地址
const getSubAppEntry = (appName, defaultPort) => {
    const envEntry = import.meta.env[`VITE_${appName.toUpperCase()}_ENTRY`]
    if (envEntry) return envEntry

    const isDev = import.meta.env.DEV
    if (isDev) {
        return `//localhost:${defaultPort}`
    } else {
        const baseUrl = import.meta.env.VITE_BASE_URL || window.location.origin
        return `${baseUrl}/${appName}`
    }
}

// 注册子应用
export const registerApps = () => {
    registerMicroApps([
        createSubAppConfig('sub-app1', 8082),
        createSubAppConfig('sub-app2', 8083)
    ], {
        beforeLoad: [(app) => console.log('[主应用] before load', app.name)],
        beforeMount: [(app) => console.log('[主应用] before mount', app.name)],
        afterMount: [(app) => console.log('[主应用] after mount', app.name)]
    })

    // 启动 qiankun
    start({
        prefetch: 'all',
        sandbox: { experimentalStyleIsolation: true, strictStyleIsolation: false },
        singular: true,
        fetch: window.fetch,
        excludeAssetFilter: (assetUrl) => {
            const whiteList = ['.html', '.js', '.css', '.json', '.woff', '.ttf', '.eot', '.svg']
            return !whiteList.some((suffix) => assetUrl.endsWith(suffix))
        }
    })
}

// 监听路由变化
router.beforeEach((to, from, next) => {
    if (to.path.startsWith('/sub-app1')) {
        const subAppPath = to.path.replace('/sub-app1', '')
        actions.setGlobalState({ subAppRoute: subAppPath, currentSubApp: 'sub-app1' })
    } else if (to.path.startsWith('/sub-app2')) {
        const subAppPath = to.path.replace('/sub-app2', '')
        actions.setGlobalState({ subAppRoute: subAppPath, currentSubApp: 'sub-app2' })
    }
    next()
})

// 导出 actions
export { actions }

